﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Threading.Tasks;

using Newtonsoft.Json;

using static System.Runtime.InteropServices.JavaScript.JSType;

namespace Aliphant.Net.Common.Http
{
    public static class HttpAgent
    {
        public async static Task<string?> Get(string url, RequestInit init)
        {
            HttpClient client = new HttpClient();
            //client.DefaultRequestHeaders.Add("Accept", "application/json");

            if (init.headers != null)
            {
                foreach (var header in init.headers)
                {
                    client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
            }

            HttpRequestMessage httpreq;
            if (init.method == "POST")
            {
                httpreq = new HttpRequestMessage(HttpMethod.Post, url);

                if (!string.IsNullOrEmpty(init.body))
                {
                    httpreq.Content = new StringContent(init.body, null, "application/json");
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(init.body))
                {
                    url = $"{url}?{init.body}";
                }
                httpreq = new HttpRequestMessage(HttpMethod.Get, url);
            }

            var response = await client.SendAsync(httpreq, HttpCompletionOption.ResponseHeadersRead);
            response.EnsureSuccessStatusCode();

            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
                return content;
            }

            return null;
        }
    }

    public class RequestInit
    {
        public string? method { get; set; }

        public IDictionary<string, string>? headers { get; set; }

        public string? body { get; set; }
    }
}
